import {
  type UploadChangeParam,
  type UploadFile,
  notification
} from 'ant-design-vue'
import { omitBy } from 'lodash-unified'
import { computed, ref } from 'vue'

import { userApi } from '@/apis'
import { TableRefHook } from '@/hooks'
import { download } from '@/utils'

import { useUserForm } from '.'

type Params = {
  getFormData: PromiseFunc
  tableRefHook: TableRefHook
}

export function useToolbar({ getFormData, tableRefHook }: Params) {
  const showImport = ref(false)
  const importLoading = ref(false)

  /**
   * 能否导出
   */
  const canExport = computed(() => {
    if (tableRefHook.tableRef.value) {
      return tableRefHook.tableRef.value.getData().length > 0
    }
    return false
  })

  const {
    show: showAdd,
    loading: addLoading,
    formModel: addFormModel,
    formRef: addFormRef
  } = useUserForm()

  function handleShowAdd() {
    showAdd.value = true
    getFormData()
  }

  function handleCloseAdd() {
    showAdd.value = false
  }

  function handleAdd() {
    addFormRef.validate().then(async () => {
      try {
        addLoading.value = true

        await userApi.createUser(addFormModel.value)

        addLoading.value = false
        handleCloseAdd()
        tableRefHook.refresh()
      } catch {
        addLoading.value = false
      }
    })
  }

  function handleShowImport() {
    showImport.value = true
  }

  function handleCloseImport() {
    showImport.value = false
  }

  async function handleTemplate() {
    const res = await userApi.exportUserTemplate()

    download(res)
  }

  async function handleUploadTemplateChange(
    info: UploadChangeParam<UploadFile<any>>
  ) {
    importLoading.value = true

    if (info.file.status === 'done') {
      importLoading.value = false

      const { success, fail } = info.file.response.data

      notification.info({
        message: `导入用户：成功${success}，失败${fail}`
      })
    }
  }

  async function handleExport() {
    const { form, pager } = tableRefHook.tableRef.value.getProxyInfo()!

    const dto = omitBy(form, value => {
      return value === null
    })

    try {
      tableRefHook.showLoading()

      const res = await userApi.exportUserPage({
        pageSize: pager.pageSize,
        pageNum: pager.currentPage,
        ...dto
      } as any)

      download(res)
    } finally {
      tableRefHook.hideLoading()
    }
  }

  return {
    showImport,
    importLoading,
    canExport,
    showAdd,
    addLoading,
    addFormModel,
    addFormRef,
    handleShowAdd,
    handleCloseAdd,
    handleAdd,
    handleShowImport,
    handleCloseImport,
    handleTemplate,
    handleUploadTemplateChange,
    handleExport
  }
}
